package com.hdl.sqlSession;

import com.hdl.config.BoundSql;
import com.hdl.pojo.Configuration;
import com.hdl.pojo.MappedStatement;
import com.hdl.utils.GenericTokenParser;
import com.hdl.utils.ParameterMapping;
import com.hdl.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hedonglin
 * @date 2020/4/21 21:43
 * @description
 */
public class SimpleExecutor implements Executor {


    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        // 1、注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2、获取sql语句 select * from user where id = #{id} and username = #{username}
            // 转换SQL语句 select * from user where id = ? and username = ? ， 转化过程中，还需要对#{}里面的值进行解析存储
        String sqlText = mappedStatement.getSql();

        BoundSql boundSql = getBoundSql(sqlText);

        // 3、获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getParseSql());

        // 4、设置参数
            // 获取到了参数类型的全路径
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            // 对应着#{}里面的值
            String content = parameterMapping.getContent();
            if (parameterClass == null || params.length == 0){
                break;
            }
            Field declaredField = parameterClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1, o);
        }

        List<E> resultList = new ArrayList<>();
        // 5、执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        while (resultSet.next()){
            Object o = resultTypeClass.newInstance();
            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                // 字段名(getColumnName下标从1开始)
                String columnName = metaData.getColumnName(i);

                // 字段值
                Object value = resultSet.getObject(columnName);

                // 使用反射或内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);

                Method writeMethod = propertyDescriptor.getWriteMethod();

                writeMethod.invoke(o, value);
            }
            resultList.add((E) o);
        }

        return resultList;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        // 1、注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2、获取sql语句
        String sqlText = mappedStatement.getSql();

        BoundSql boundSql = getBoundSql(sqlText);

        // 3、获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getParseSql());

        // 4、设置参数
        // 获取到了参数类型的全路径
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            // 对应着#{}里面的值
            String content = parameterMapping.getContent();
            if (parameterClass == null || params.length == 0){
                break;
            }
            Field declaredField = parameterClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1, o);
        }
        connection.setAutoCommit(false);
        // 5、执行sql
        int result = preparedStatement.executeUpdate();
        // 6、提交事务
        connection.commit();
       return result;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }

        return null;
    }

    /**
     * 完成对#{}的解析工作， 1、将#{}使用?进行代替，2、解析出#{}里面的值进行存储
     */
    private BoundSql getBoundSql(String sqlText) {
        // 标记处理类： 配置标记解析器来完成对占位符的解析工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        // 标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        // 解析后的SQL
        String parseSql = genericTokenParser.parse(sqlText);

        // #{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(parseSql, parameterMappings);
    }


}
